<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖动DIV</title>
    <style>
        .d1 {
            position: relative;
            left: 100px;
            width: 100px;
            height: 100px;
            background: linear-gradient(to right, rgb(41, 152, 236) 0%, rgb(143, 60, 238) 100%);
        }
    </style>
</head>

<body>
    <!--<button id="btn1">按钮</button>-->
    <div class="d1"></div>
    <script>
        // var btn1 = document.getElementById("btn1");
        var d1 = document.getElementsByClassName("d1")[0];
        var startX, startY, nowX, nowY, changeX, changeY;
        // 保存移动后的位置
        var positionX = 0,
            positionY = 0;

        // function test() {
        //     alert("点击事件");
        // }
        //
        // if (document.addEventListener) {
        //     btn1.addEventListener("click", test, false);
        // } else {
        //     btn1.attachEvent("onclick", test);
        // }

        d1.addEventListener("touchstart", function (e) {
            var tt = e.targetTouches[0];
            // console.log(e.changedTouches);
            // console.log(e.touches);
            // console.log(e.targetTouches);
            startX = tt.clientX;
            startY = tt.clientY;

        })
        d1.addEventListener("touchmove", function (e) {
            var tt = e.targetTouches[0];
            console.log("拖动中");
            // console.log(e.targetTouches);
            nowX = tt.clientX;
            nowY = tt.clientY;
            changeX = nowX - startX;
            changeY = nowY - startY;
            console.log(changeX);
            console.log(changeY);
            d1.style.transform = "translate(" + (changeX + positionX) + "px," + (changeY + positionY) + "px)";
        })
        d1.addEventListener("touchend", function (e) {
            console.log("触屏结束");
            var ct = e.changedTouches[0];
            nowX = ct.clientX;
            nowY = ct.clientY;
            positionX += nowX - startX;
            positionY += nowY - startY;

        })


    </script>
</body>

</html>